import re

from datetime import datetime, timedelta
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext as _
from rest_framework import serializers
from rest_framework_jwt.compat import Serializer
from rest_framework_jwt.utils import jwt_encode_handler

from users.models import VerifyCode
from utils.payload_handler import jwt_payload_handler
from ImageThinking.settings import REGEX_MOBILE

User = get_user_model()


class MobileUserSerializer(Serializer):
    def __init__(self, *args, **kwargs):
        """
        Dynamically add the USERNAME_FIELD to self.fields.
        """
        super(MobileUserSerializer, self).__init__(*args, **kwargs)

        self.fields['mobile'] = serializers.CharField(required=True, write_only=True, max_length=11, min_length=11, label="手机号码",
                                 error_messages={
                                     "blank": "请输入手机号码",
                                     "required": "请输入手机号码",
                                     "max_length": "手机号码格式错误",
                                     "min_length": "手机号码格式错误"
                                 })  # 手机号
        self.fields['code'] = serializers.CharField(required=True, write_only=True, max_length=6, min_length=6, label="验证码",
                                 error_messages={
                                     "blank": "请输入验证码",
                                     "required": "请输入验证码",
                                     "max_length": "验证码格式错误",
                                     "min_length": "验证码格式错误"
                                 })  # 验证码
        # self.fields['remember'] = serializers.IntegerField(default=60, allow_null=True)  # 过期时间

    def validate(self, attrs):

        credentials = {
            'mobile': attrs.get('mobile'),
            'code': attrs.get('code'),
            # 'remember': attrs.get('remember'),
        }

        if all(credentials.values()):
            # 验证手机号码是否合法
            if not re.match(REGEX_MOBILE, credentials.get('mobile')):
                raise serializers.ValidationError("手机号码非法")

            # 手机是否注册
            try:
                user = User.objects.get(mobile=credentials.get('mobile'))
            except User.DoesNotExist:
                raise serializers.ValidationError('用户不存在')

            # 验证码校验
            verify_records = VerifyCode.objects.filter(mobile=credentials.get('mobile')).order_by("-add_time")
            if verify_records:
                last_record = verify_records[0]

                one_mintes_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
                if one_mintes_ago > last_record.add_time.replace(tzinfo=None):
                    raise serializers.ValidationError("验证码过期")
                if last_record.code != credentials.get('code'):
                    raise serializers.ValidationError("验证码错误")
            else:
                raise serializers.ValidationError("验证码错误")

            if user:
                # exp = datetime.utcnow() + timedelta(seconds=credentials.get('remember'))  # 过期时间
                # payload = jwt_payload_handler(user, exp)
                payload = jwt_payload_handler(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }

            else:
                msg = _('无法使用提供的Token登录')
                raise serializers.ValidationError(msg)
        else:
            msg = _('必须包含手机号和验证码')
            # msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)


class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    # def validate_mobile(self, attrs):